<?php
/**
 *
 * @Author nikm $
 *
 * @Date 2011-12-20 $
 */

if(!defined('FROM_INDEX')) exit('Invalid request');

require ROOT_PATH.'include/lib/cache.func.php';
require ROOT_PATH.'include/lib/cookie.func.php';
require ROOT_PATH.'include/lib/session.func.php';
require ROOT_PATH.'include/sql/sql_functions.php';

class masterObj
{
	var $config = array();
	var $request = array();
	var $response = array();
	
	var $act = '';
	var $user = array();
	var $session = array();
	
	var $from_id = '';
	var $to_id = '';
	var $page_limit = '';
	var $page_num = '';
	
	function __construct($request)
	{
		load_setting('config_global');
		
		$this->request = $request;
		$this->act = $request['act'];
		
		$this->from_id = isset($request['from_id']) ? $request['from_id'] : '';
		$this->from_id = max(0, (int)$this->from_id);
		$this->to_id = isset($request['to_id']) ? $request['to_id'] : '';
		$this->to_id = max(0, (int)$this->to_id);
		
		$this->page_limit = isset($request['count']) ? min(MAX_PER_PAGE, max(0, (int)$request['count'])) : DEFAULT_PER_PAGE;
		$this->page_num = isset($request['page']) ? max(0, (int)$request['page'] - 1) : 0;
		
		$auth_code = cookie_get('auth');
		
		$password = $uid = '';
		if($auth_code)
		{
			list($password, $uid) = explode("\t", authcode($authcode, 'DECODE'));
		}
		
		$user = get_user($uid);
		if(isset($user['id']) && $user['id'] > 0)
		{
			$auth_code = authcode($user['password'].'\t'.$user['id'], 'ENCODE');
			cookie_set('auth', $auth_code);
			
			$this->user = $user;
		}
		else
		{
			$this->user['id'] = -1;
			$this->user['name'] = 'guest';
			$this->user['group_id'] = -1;
			
			cookie_delete('auth');
		}
		
		$this->_checkUser();
		
		$this->updateSession();
	}
	
	function message($code, $status)
	{
		show_msg($code, $status);
	}
	
	function showResponse()
	{
		$json = '';
		if(is_array($this->response) && count($this->response) > 0)
		{
			$results = array_merge(array('version' => API_VERSION), $this->response);
			$json = @json_encode($results);
		}
		
		requestLog($this->request, (string)$json, $this->response['status']);
				
		echo $json;		
		exit();
	}
	
	function updateSession()
	{
		$sid = cookie_get('sid');
		$session = session_get($sid);
		
		if(check_array($session))
		{
			$this->session = $session;
		}
		else
		{
			$this->session = session_init($sid);
		}
		
		$this->session['uid'] = $this->user['id'];
		$this->session['user_name'] = $this->user['name'];
		$this->session['group_id'] = $this->user['group_id'];
		$this->session['ip'] = client_ip();
		
		session_update($this->session);
	}
	
	/**
	 * 
	 * Check if user login & has permission
	 */
	function _checkUser()
	{
		return true;
		
		//TODO
		$this->message('001', STATUS_E);
	}
	
	/**
	 * 
	 * Get user info by uid, if uid is null, return current user
	 * 
	 * @param string $uid
	 * 
	 * @return array $user
	 */
	function _user($uid='')
	{
		return get_user($uid);	
	}
}